package com;

/**
 * @author Ricky
 * @date 2020-9-3
 */

import com.annotation.SocketEvent;
import com.alibaba.fastjson.JSONObject;
import com.bean.*;
import com.bean.param.*;
import com.config.Config;
import com.consts.Const;
import com.socketio.SocketIoServeice;
import com.thread.Distribute;
import com.util.*;
import lombok.extern.slf4j.Slf4j;

import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 统一业务2.0接口
 */
@Slf4j
public class UnifiedBusiness2 {
    private static final Config CONFIG = ConfigUtil.getConfig();

    /**
     * 获取组织机构树
     *
     * @param dwbm
     * @return 组织机构树形数据
     * @throws Exception
     */
    @SocketEvent
    public static List<Map<String, Object>> getUnitTreeList(String dwbm) throws Exception {
        JSONObject param = new JSONObject();
        param.put("dwbm", dwbm);
        Map<String, Object> unitData =  CsbUtil.SendRequest(Const.get_unit_list, param);
        List<Map<String, Object>> dataSource = (List<Map<String, Object>>) unitData.get("data");
        Map<String, String> fields = new HashMap<>();
        fields.put("dwbm", "DWBM");
        fields.put("dwmc", "DWMC");
        fields.put("fdwbm", "FDWBM");
        fields.put("dwjb", "DWJB");
        return DataUtil.StructuredObject(dataSource, "fdwbm", "dwbm", dwbm, fields);
    }

    /**
     * 用户登录
     *
     * @param argument
     * @return
     */
    @SocketEvent
    public static Map<String, Object> loginVerification(LoginParam argument) throws Exception {
        Map<String, Object> userData = CsbUtil.SendRequest(Const.login_verification, argument);
        // 获取登录信息
        Map<String, Object> loginInfo = (Map<String, Object>) userData.get("data");
        // 获取用户角色
        Map<String, Object> unit = (Map<String, Object>) loginInfo.get("unit");
        List<Map<String, Object>> departments = (List<Map<String, Object>>) loginInfo.get("departments");
        Map<String, Object> userInfo = (Map<String, Object>) loginInfo.get("userInfo");

        Map<String, Object> result = new HashMap<>();
        result.put("DWBM", unit.get("dwbm"));
        result.put("DWMC", unit.get("dwmc"));
        result.put("BMBM", departments != null && departments.size() > 0 ? departments.get(0).get("bmbm") : userInfo.get(""));
        result.put("BMMC", departments != null && departments.size() > 0 ? departments.get(0).get("bmmc") : userInfo.get(""));
        result.put("GH", userInfo.get("rybm"));
        result.put("MC", userInfo.get("mc"));
        result.put("DLBM", userInfo.get("dlbm"));
        result.put("XB", userInfo.get("xb"));
        result.put("ZP", userInfo.get("zp"));
        // TODO 密码加密
        result.put("KL", argument.getKl());
//        session.setAttribute("currentUser", result);
        return result;
    }

    /**
     * 根据人员编码获取用户信息
     *
     * @param argument
     * @return
     */
    @SocketEvent
    public static Map<String, Object> getUserInfoByCode(UserInfoByCodeParam argument) throws Exception {

        Map<String, Object> userData = CsbUtil.SendRequest(Const.get_user_info, argument);
        // 获取用户信息
        Map<String, Object> userInfo = (Map<String, Object>) userData.get("data");
        // 获取用户角色
        List<Map<String, Object>> roles = (List<Map<String, Object>>) userInfo.get("roles");

        Map<String, Object> result = new HashMap<>();
        result.put("DWBM", userInfo.get("dwbm"));
        result.put("DWMC", userInfo.get("dwmc"));
        result.put("BMBM", roles != null && roles.size() > 0 ? roles.get(0).get("bmbm") : userInfo.get(""));
        result.put("BMMC", roles != null && roles.size() > 0 ? roles.get(0).get("bmmc") : userInfo.get(""));
        result.put("GH", userInfo.get("rybm"));
        result.put("MC", userInfo.get("mc"));
        result.put("DLBM", userInfo.get("dlbm"));
        result.put("KL", new String(Base64.getDecoder().decode(Base64.getDecoder().decode(userInfo.get("bz").toString()))));
        result.put("XB", userInfo.get("xb"));
        result.put("ZP", userInfo.get("zp"));

        return result;
    }

    /**
     * 根据关键字查询案件列表
     *
     * @param argument
     * @return
     * @throws Exception
     */
    @SocketEvent
    public static List<Map<String, Object>> getCaseList(CaseListParam argument) throws Exception {
        argument.setBlzt("D");
        argument.setCurrentPage(0);
        argument.setPageSize(99999);
        Map<String, Object> caseData = CsbUtil.SendRequest(Const.get_case_list, argument);
        // 获取案件列表信息
        Map<String, Object> caseInfo = (Map<String, Object>) caseData.get("data");
        caseInfo = (Map<String, Object>) caseInfo.get("zbajlb");

        List<Map<String, Object>> caseList = (List<Map<String, Object>>) caseInfo.get("records");

        List<Map<String, Object>> result = new ArrayList<>();

        for (Map<String, Object> item : caseList) {
            Map<String, Object> info = new HashMap<>();
            info.put("BMSAH", item.get("bmsah"));
            info.put("AJMC", item.get("ajmc"));
            info.put("AJLB_MC", item.get("ajlbmc"));
            info.put("DQJD", item.get("bljd"));
            info.put("CBDW_BM", item.get("cbdwbm"));
            result.add(info);
        }
        return result;
    }

    /**
     * 根据部门受案号查询案件信息
     *
     * @param bmsah
     * @return
     * @throws Exception
     */
    @SocketEvent
    public static Map<String, Object> getCaseInfoByCode(String bmsah) throws Exception {
        JSONObject param = new JSONObject();
        param.put("bmsah", new String[]{bmsah});
        Map<String, Object> caseData = CsbUtil.SendRequest(Const.get_case_info, param);
        // 获取案件信息
        List<Map<String, Object>> caseInfo = (List<Map<String, Object>>) caseData.get("data");

        Map<String, Object> result = new HashMap<>();

        if (caseInfo.size() > 0) {
            result.put("case", caseInfo.get(0));
            List<Map<String, Object>> perpetrator = (List<Map<String, Object>>) caseInfo.get(0).get("zrrxx");
            result.put("perpetrator", perpetrator);
        }
        return result;
    }

    /**
     * 获取案件证据目录
     *
     * @param argument
     * @return
     * @throws Exception
     */
    @SocketEvent
    public static Map<String, Object> getEvidenceMaterialCatalog(EvidenceMaterialCatalogParam argument) throws Exception {
        Map<String, Object> res = new HashMap<>();
        res.put("dossier", getDossierCatalog(argument.getDwbm(), argument.getBmsah()));
        res.put("docDossier", getDocDossierCatalog(argument.getBmsah()));
        return res;
    }


    /**
     * 下载案件证据目录
     *
     * @param argument
     * @throws Exception
     */
    @SocketEvent
    public static void downloadEvidenceMaterialCatalog(DownloadEvidenceMaterialCatalogParam argument) throws Exception {
        String BMSAH = argument.getBMSAH();
        String UnitCode = argument.getCBDW_BM();
        String dbFile = argument.getCurrentDBFile();

        try (DBUtil dbUtil = new DBUtil(dbFile)) {
            // 获取电子卷宗分表信息
            List<Map<String, Object>> subTables = dbUtil.executeQuerys("select WJXH,WJBM,substr(wjbm,15)[INDEX] from yx_dzjz_tpb order by cast(substr(wjbm,15)as number)");
            // 获取已下载电子卷宗目录信息
            List<Map<String, Object>> existEvidence = dbUtil.executeQuerys("select wjxh id,'0' type from yx_dzjz_jzmlwj union all select wsbh, '1' from yx_ws_ajjzwj");

            // 下载电子卷宗目录
            Dossier dossier = getDossierCatalog(UnitCode, BMSAH);

            Map<String, Object> res = subDossierFile(dossier.getFileCatalog(), subTables);
            Map<String, String> tables = (Map<String, String>) res.get("table");

            dbUtil.executeUpdate((List<SQLiteArgument>) res.get("sqls"));

            List<SQLiteArgument> execSqls = new LinkedList<>();

            execSqls.addAll(EvidenceMaterialServer.addDossierCatalog(dossier.getCatalog()));

            for (DossierFileCatalog item : dossier.getFileCatalog()) {
                //过滤已下载文件
                if (existEvidence != null && existEvidence.stream().filter(x -> x.get("type").equals("0") && x.get("id").equals(item.getWJXH())).collect(Collectors.toList()).size() > 0) {
                    continue;
                }

                //设置卷宗所在表名
                item.setWJBM(tables.get(item.getWJXH()));
                execSqls.addAll(EvidenceMaterialServer.addDossierFile(item));
            }

            // 下载文书卷宗目录
            DocDossier docDossier = getDocDossierCatalog(BMSAH);
            execSqls.addAll(EvidenceMaterialServer.addDocDossierCatalog(docDossier.getCatalog()));
            for (DocDossierFileCatalog item : docDossier.getFileCatalog()) {
                //过滤已下载文件
                if (existEvidence != null && existEvidence.stream().filter(x -> x.get("type").equals("1") && x.get("id").equals(item.getWSBH())).collect(Collectors.toList()).size() > 0) {
                    continue;
                }
                execSqls.addAll(EvidenceMaterialServer.addDocDossierFile(item));
            }

            dbUtil.executeUpdate(execSqls);
        }
    }

    /**
     * 初始化案件文件
     *
     * @param argument
     * @return
     * @throws Exception
     */
    @SocketEvent
    public static String initDatabaseFile(InitDatabaseFileParam argument) throws Exception {
        String dbFilePath = argument.getCasePath();
        Map<String, Object> userInfo = getUserInfoByCode(argument.getUserInfoByCodeParam());
        Map<String, Object> caseInfo = getCaseInfoByCode(argument.getBmsah());
        List<Map<String, Object>> perpetrator = (List<Map<String, Object>>) caseInfo.get("perpetrator");
        caseInfo = (Map<String, Object>) caseInfo.get("case");

        try (InputStream templateInputStream = new FileInputStream("config/template.case")) {
            Files.copy(templateInputStream, Paths.get(dbFilePath), StandardCopyOption.REPLACE_EXISTING);
        }

        try (DBUtil dbUtil = new DBUtil(dbFilePath)) {
            List<SQLiteArgument> sqLiteArguments = new ArrayList<>();
            sqLiteArguments.add(EvidenceMaterialServer.addUserInfo(userInfo));
            sqLiteArguments.add(EvidenceMaterialServer.addCaseInfo(caseInfo));
            sqLiteArguments.addAll(EvidenceMaterialServer.addPerpetrator(caseInfo.get("bmsah").toString(), caseInfo.get("tysah").toString(), perpetrator));

//        if (argument.getBooleanValue("isInitCatalog")) {
//            try {
//                ServerResponse response = DownloadEvidenceCatalog(argument.getString("bmsah"));
//                Object dataSource = response.getData();
//                if (response.isSuccess() && !StringUtils.isEmpty(dataSource) && !"null".equals(dataSource)) {
//                    sqLiteArguments.add(EvidenceMaterialServer.addEvidenceCatalog(response.getData().toString()));
//                }
//            } catch (Exception e) {
//                log.error("下载阅卷辅助数据失败", e);
//            }
//        }

            dbUtil.executeUpdate(sqLiteArguments);

            return dbFilePath;
        }
    }

    /**
     * 根据证据材料编号下载材料文件
     *
     * @param argument
     * @return
     * @throws Exception
     */
    @SocketEvent
    public static void downLoadEvidenceMaterialByCodes(DownLoadEvidenceMaterialByCodesParam argument) throws Exception {
        List<String> files = argument.getFiles();
        String dbFilePath = argument.getDbFile();

        try (DBUtil dbUtil = new DBUtil(dbFilePath)) {
            List<Map<String, Object>> res = dbUtil.executeQuerys(EvidenceMaterialServer.getDownloadMaterial(files));

            List<DossierFileCatalog> dossierFileCatalogs = new ArrayList<>();
            List<DocDossierFileCatalog> docDossierFileCatalogs = new ArrayList<>();

            DossierFileCatalog dossierFileCatalog;
            DocDossierFileCatalog docDossierFileCatalog;
            for (Map<String, Object> item : res) {
                if ("1".equals(item.get("WJLX"))) {
                    dossierFileCatalog = new DossierFileCatalog();
                    dossierFileCatalog.setBMSAH(item.get("BMSAH").toString());
                    dossierFileCatalog.setWJMC(item.get("WJMC").toString());
                    dossierFileCatalog.setDWBM(item.get("DWBM").toString());
                    dossierFileCatalog.setWJXH(item.get("WJXH").toString());
                    dossierFileCatalog.setWJXSMC(item.get("WJXSMC").toString());
                    dossierFileCatalog.setWJHZ(item.get("WJHZ").toString());
                    dossierFileCatalog.setWJBM(item.get("WJBM").toString());
                    dossierFileCatalogs.add(dossierFileCatalog);
                } else {
                    docDossierFileCatalog = new DocDossierFileCatalog();
                    docDossierFileCatalog.setWSBH(item.get("WJXH").toString());
                    docDossierFileCatalog.setWJMC(item.get("WJMC").toString());
                    docDossierFileCatalog.setWJKZM(item.get("WJHZ").toString());
                    docDossierFileCatalogs.add(docDossierFileCatalog);
                }
            }

            Distribute.distributeAndRun(dbUtil, dossierFileCatalogs, docDossierFileCatalogs, progress -> {

            });
        }
    }

    @SocketEvent
    public static void downLoadEvidenceMaterial(DownLoadEvidenceMaterialParam param) throws Exception {
        String dbFilePath = param.getDbPath();
        try (DBUtil dbUtil = new DBUtil(dbFilePath)) {
            // 保存目录
            List<DossierCatalog> dossierCatalogs = param.getCatalog();
            List<DocDossierCatalog> docDossierCatalogs = param.getDocCatalog();

            List<SQLiteArgument> execSqls = new LinkedList<>();

            execSqls.addAll(EvidenceMaterialServer.addDossierCatalog(dossierCatalogs));
            execSqls.addAll(EvidenceMaterialServer.addDocDossierCatalog(docDossierCatalogs));
            dbUtil.executeUpdate(execSqls);

            // 保存文件
            List<DossierFileCatalog> dossierFileCatalogs = param.getFileCatalog();
            List<DocDossierFileCatalog> docDossierFileCatalogs = param.getDocFileCatalog();
            String socketId = param.getSocketId();
            String eventName = param.getEventName();
            Distribute.distributeAndRun(dbUtil, dossierFileCatalogs, docDossierFileCatalogs, progress -> {
                System.out.println(progress.getID());
                SocketIoServeice.sendEvent(socketId, eventName, progress);
            });
        }
    }

    /**
     * 根据证据材料编号在线获取证据材料文件
     *
     * @param argument
     * @return
     * @throws Exception
     */
    @SocketEvent
    public static String getEvidenceMaterialByCode(EvidenceMaterialByCodeParam argument) throws Exception {
        String pdfStr;
        String fileID = argument.getFileID();
        String DbPath = argument.getDbPath();
        int fileType = argument.getFileType();

        try (DBUtil dbUtil = new DBUtil(DbPath)) {
            List<SQLiteArgument> args = new ArrayList<>();
            //开始下载卷宗文件
            if (fileType == 0) {
                Map<String, Object> res = dbUtil.executeQuery(EvidenceMaterialServer.getDossierPdf(fileID));

                if (!StringUtils.isEmpty(res.get("PDF"))) {
                    return res.get("PDF").toString();
                }

                DossierFileCatalog dossierFileCatalog = new DossierFileCatalog();
                dossierFileCatalog.setBMSAH(res.get("BMSAH").toString());
                dossierFileCatalog.setWJMC(res.get("WJMC").toString());
                dossierFileCatalog.setDWBM(res.get("DWBM").toString());
                dossierFileCatalog.setWJXH(res.get("WJXH").toString());
                dossierFileCatalog.setWJXSMC(res.get("WJXSMC").toString());
                dossierFileCatalog.setWJHZ(res.get("WJHZ").toString());
                dossierFileCatalog.setWJBM(res.get("WJBM").toString());
                dossierFileCatalog.download(dbUtil, null);

                pdfStr = dossierFileCatalog.getPDF();
            } else {
                //开始下载文书文件
                Map<String, Object> res = dbUtil.executeQuery(EvidenceMaterialServer.getDocDossierPdf(fileID));

                if (res == null) {
                    return null;
                }
                if (!StringUtils.isEmpty(res.get("PDF"))) {
                    return res.get("PDF").toString();
                }
                DocDossierFileCatalog docDossierFile = new DocDossierFileCatalog();
                docDossierFile.setWSBH(res.get("WSBH").toString());
                docDossierFile.setWJMC(res.get("WJMC").toString());
                docDossierFile.setWJKZM(res.get("WJKZM").toString());

                docDossierFile.download(dbUtil, null);
                pdfStr = docDossierFile.getPDF();
            }
            return pdfStr;
        }
    }


    /**
     * 获取证据材料文件图片
     *
     * @param argument
     * @return
     * @throws Exception
     */
    @SocketEvent
    public List<Map<String, Object>> GetEvidenceMaterial(EvidenceMaterialParam argument) throws Exception {
        DBUtil dbUtil = new DBUtil(argument.getDbPath());
        try {
            String sid = argument.getSid();
            List<String> files = argument.getFiles();
            String fid = String.format("'%s'", String.join("','", files));

            if (files.size() > 0) {
                List<Map<String, Object>> downloadFile = dbUtil.executeQuerys(String.format("select wjxh fileID,0 fileType from yx_dzjz_jzmlwj where wjxh in (%s) and IFNULL(PDF,'') ='' union select wsbh,1 from yx_ws_ajjzwj where wsbh in (%s) and IFNULL(PDF,'') =''", fid, fid));
                for (Map<String, Object> item : downloadFile) {
//                    item.put("dbPath", argument.getDbPath());
                    EvidenceMaterialByCodeParam evidenceMaterialByCodeParam = new EvidenceMaterialByCodeParam();
                    evidenceMaterialByCodeParam.setDbPath(argument.getDbPath());
                    evidenceMaterialByCodeParam.setFileID(item.get("fileID").toString());
                    evidenceMaterialByCodeParam.setFileType(0);
                    getEvidenceMaterialByCode(evidenceMaterialByCodeParam);
                }
            }

            //获取图片对应表
            StringBuilder sb = new StringBuilder();
            if (StringUtils.isEmpty(sid)) {
                sb.append(String.format("select WJBM,'select WJXH WJID,ID,IMG,[ORDER] from '||WJBM||' where WJXH in ('''||group_concat(wjxh,''',''')||''')' SQL from yx_dzjz_tpb where wjxh in(%s) group by wjbm ", fid));
                sb.append("union ");
                sb.append(String.format("select 'yx_ws_ajjztpl' WJBM,'select WSBH WJID,ID,IMG,[ORDER] from yx_ws_ajjztpl where WSBH in ('''||group_concat(wsbh,''',''')||''')' SQL from yx_ws_ajjztpl where wsbh in (%s) ", fid));
                sb.append("union ");
                sb.append(String.format("select 'yx_fj_tpl' WJBM,'select WJID WJID,ID,IMG,[ORDER] from yx_fj_tpl where WJID in ('''||group_concat(wjid,''',''')||''')' SQL from yx_fj_tpl where wjid in (%s)", fid));
            } else {
                sb.append(String.format("select WJBM,'select WJXH WJID,ID,IMG,[ORDER] from '||WJBM||' where WJXH in ('''||group_concat(wjxh,''',''')||''')' SQL from yx_dzjz_tpb where wjxh in(%s) or wjxh in(select filecode from yx_ct_ys where path != '' and sid = '%s' group by filecode)  group by wjbm ", fid, sid));
                sb.append("union ");
                sb.append(String.format("select 'yx_ws_ajjztpl' WJBM,'select WSBH WJID,ID,IMG,[ORDER] from yx_ws_ajjztpl where WSBH in ('''||group_concat(wsbh,''',''')||''')' SQL from yx_ws_ajjztpl where wsbh in (%s) or wsbh in(select filecode from yx_ct_ys where path != '' and sid = '%s' group by filecode)", fid, sid));
                sb.append("union ");
                sb.append(String.format("select 'yx_fj_tpl' WJBM,'select WJID WJID,ID,IMG,[ORDER] from yx_fj_tpl where WJID in ('''||group_concat(wjid,''',''')||''')' SQL from yx_fj_tpl where wjid in (%s) or wjid in(select filecode from yx_ct_ys where path != '' and sid = '%s' group by filecode)", fid, sid));
            }
            List<Map<String, Object>> tables = dbUtil.executeQuerys(sb.toString());

            List<String> arr = new ArrayList<>();
            for (Map<String, Object> item : tables) {
                if (StringUtils.isEmpty(item.get("SQL")) || item.get("SQL").equals(0)) {
                    continue;
                }
                arr.add(item.get("SQL").toString());
            }
            if (arr.size() <= 0) {
                return null;
            }
            String sql = String.join(" union ", arr);


            return dbUtil.executeQuerys(sql);
        } finally {
            dbUtil.destroyed();
        }
    }

//    /**
//     * 获取阅卷辅助数据
//     * @param bmsah
//     * @return
//     * @throws Exception
//     */
//    public ServerResponse DownloadEvidenceCatalog(String bmsah) throws Exception {
//        String url = configuration.getGetEvidenceCatalog() + URLEncoder.encode(bmsah, "utf-8");
//        Map<String, Object> res = HttpUtil.get(url);
//
//        return res.get("data");
//    }

    /**
     * 获取电子卷宗目录
     *
     * @param dwbm
     * @param bmsah
     * @return
     * @throws Exception
     */
    private static Dossier getDossierCatalog(String dwbm, String bmsah) throws Exception {
        Map<String, String> param = new HashMap<>();
        param.put("dwbm", dwbm);
        param.put("bmsah", bmsah);

        Map<String, Object> response = CsbUtil.SendRequest(Const.get_dossier_catalog, param);
        Map<String, Object> dossierCatalogs = (Map<String, Object>) response.get("data");
        List<Map<String, String>> catalog = (List<Map<String, String>>) dossierCatalogs.get("jzml");

        Dossier dossier = new Dossier();

        List<DossierCatalog> dossierCatalogList = new ArrayList<>();


        for (Map<String, String> item : catalog) {
            DossierCatalog dossierCatalog = new DossierCatalog();
            dossierCatalog.setNodeNo(item.get("mlbh"));
            dossierCatalog.setNodeParentNo(item.get("fmlbh"));
            dossierCatalog.setJZBH(item.get("jzbh"));
            dossierCatalog.setMLLX(item.get("mllx"));
            dossierCatalog.setMLBH(item.get("mlbh"));
            dossierCatalog.setFMLBH(item.get("fmlbh"));
            dossierCatalog.setMLXSMC(item.get("mlxsmc"));
            dossierCatalog.setMLSXH(item.get("mlsxh"));

            dossierCatalog.setBMSAH("");
            dossierCatalog.setDWBM(dwbm);
            dossierCatalog.setMLBM("");
            dossierCatalog.setMLXX("");
            dossierCatalog.setSFSC("N");
            dossierCatalog.setSFSM("");
            dossierCatalog.setSSLBBM("");
            dossierCatalog.setSSLBMC("");

            dossierCatalog.setNodeName(dossierCatalog.getMLXSMC());
            dossierCatalogList.add(dossierCatalog);
        }
        dossier.setCatalog(dossierCatalogList);

        List<DossierFileCatalog> dossierFileCatalogList = new ArrayList<>();

        List<Map<String, String>> fileCatalog = (List<Map<String, String>>) dossierCatalogs.get("jzmlwj");

        for (Map<String, String> item : fileCatalog) {
            DossierFileCatalog dossierCatalog = new DossierFileCatalog();
            dossierCatalog.setNodeNo(item.get("wjxh"));
            dossierCatalog.setNodeParentNo(item.get("mlbh"));
            dossierCatalog.setJZBH(item.get("jzbh"));
            dossierCatalog.setMLBH(item.get("mlbh"));
            dossierCatalog.setWJXH(item.get("wjxh"));
            dossierCatalog.setSFSC("N");
            dossierCatalog.setDWBM(dwbm);
            dossierCatalog.setBMSAH("");
            dossierCatalog.setWJLJ(item.get("wjlj"));
            dossierCatalog.setWJMC(item.get("wjxsmc"));
            dossierCatalog.setWJXSMC(item.get("wjxsmc"));
            dossierCatalog.setWJHZ(item.get("wjhz"));
            dossierCatalog.setWJKSY(item.get("wjksy"));
            dossierCatalog.setWJJSY(item.get("wjjsy"));
            dossierCatalog.setWJSXH(item.get("wjsxh"));

            dossierCatalog.setWJBZXX("");
            dossierCatalog.setWJYZBZ("");
            dossierCatalog.setWJZDY("");
            dossierCatalog.setSSLBBM("");

            dossierCatalog.setNodeName(dossierCatalog.getWJXSMC());
            dossierCatalog.setSSLBMC("");
            dossierFileCatalogList.add(dossierCatalog);
        }
        dossier.setFileCatalog(dossierFileCatalogList);


        return dossier;
    }

    /**
     * 获取文书卷宗目录
     *
     * @param bmsah
     * @return
     * @throws Exception
     */
    private static DocDossier getDocDossierCatalog(String bmsah) throws Exception {
        JSONObject param = new JSONObject();
        param.put("bmsah", bmsah);
        param.put("sfxyfj", true);
        Map<String, Object> response =  CsbUtil.SendRequest(Const.get_docDossier_catalog, param);
        List<Map<String, Object>> docDossierCatalogs = (List<Map<String, Object>>) response.get("data");

        return GetDocDossierCatalog(bmsah, docDossierCatalogs, null);
    }

    /**
     * 获取文书卷宗目录关系对象
     *
     * @param bmsah
     * @param dataSource
     * @param parentCode
     * @return
     */
    private static DocDossier GetDocDossierCatalog(String bmsah, List<Map<String, Object>> dataSource, String parentCode) {
        DocDossier result = new DocDossier();

        List<DocDossierCatalog> catalogs = new ArrayList<>();
        List<DocDossierFileCatalog> fileCatalogs = new ArrayList<>();

        for (Map<String, Object> item : dataSource) {
            String major;
            if (StringUtils.isEmpty(item.get("jzwjh"))) {
                major = item.get("jzmlh").toString();
                DocDossierCatalog catalog = new DocDossierCatalog();

                catalog.setNodeNo(major);
                catalog.setNodeParentNo(item.get("fjzmlh") == null ? "-1" : item.get("fjzmlh").toString());
                catalog.setBMSAH(bmsah);
                catalog.setSFSC("N");
                catalog.setDWBM("");
                catalog.setJZMLH(major);
                catalog.setJZMLMC(StringUtils.isEmpty(item.get("jzmlmc")) ? "" : item.get("jzmlmc").toString());
                catalog.setJZMLBM("");
                catalog.setJZFMLH(catalog.getNodeParentNo());
                catalog.setJZMLLX(StringUtils.isEmpty(item.get("jzmllx")) ? "" : item.get("jzmllx").toString());

                catalog.setNodeName(catalog.getJZMLMC());
                catalogs.add(catalog);
            } else {
                DocDossierFileCatalog fileCatalog = new DocDossierFileCatalog();
                major = item.get("jzwjh").toString();
                fileCatalog.setNodeNo(item.get("jzwjh").toString());

                fileCatalog.setNodeParentNo(parentCode);
                fileCatalog.setBMSAH(bmsah);
                fileCatalog.setSFSC("N");
                fileCatalog.setDWBM("");
                fileCatalog.setJZMLH(StringUtils.isEmpty(item.get("jzmlh")) ? "" : item.get("jzmlh").toString());
                fileCatalog.setWSBH(StringUtils.isEmpty(item.get("jzwjh")) ? "" : item.get("jzwjh").toString());

                fileCatalog.setWJMC(StringUtils.isEmpty(item.get("wjmc")) ? "" : item.get("wjmc").toString());

                fileCatalog.setWJLX(StringUtils.isEmpty(item.get("wjlx")) ? "" : item.get("wjlx").toString());

                fileCatalog.setWSCFLJ(StringUtils.isEmpty(item.get("wjcflj")) ? "" : item.get("wjcflj").toString());

                fileCatalog.setFWSBH(StringUtils.isEmpty(item.get("fwjbh")) ? "" : item.get("fwjbh").toString());

                fileCatalog.setNZRGH("");
                fileCatalog.setWJKZM(StringUtils.isEmpty(item.get("wjkzm")) ? "" : item.get("wjkzm").toString().replace(".", ""));
                fileCatalog.setRJRGH(StringUtils.isEmpty(item.get("rjrybm")) ? "" : item.get("rjrybm").toString());

                fileCatalog.setGXYWBMS("");
                fileCatalog.setSFKYGX("");
                fileCatalog.setWSMBBH("");
                fileCatalog.setYYZT("");

                fileCatalog.setNodeName(fileCatalog.getWJMC());
                fileCatalogs.add(fileCatalog);
            }
            if (item.containsKey("children") && item.get("children") != null) {
                DocDossier children = GetDocDossierCatalog(bmsah, (List<Map<String, Object>>) item.get("children"), major);
                if (children.getCatalog() != null) {
                    catalogs.addAll(children.getCatalog());
                }
                if (children.getFileCatalog() != null) {
                    fileCatalogs.addAll(children.getFileCatalog());
                }
            }
        }

        result.setCatalog(catalogs);
        result.setFileCatalog(fileCatalogs);

        return result;
    }

    private static Map<String, Object> subDossierFile(List<DossierFileCatalog> dossierFiles, List<Map<String, Object>> dossierTables) {
        Map<String, String> tables = new HashMap<>();

        if (dossierTables != null) {
            // 获取已分表卷宗
            for (Map<String, Object> item : dossierTables) {
                if (!tables.containsKey(item.get("WJXH").toString())) {
                    tables.put(item.get("WJXH").toString(), item.get("WJBM").toString());
                }
            }
        }

        int pageIndex = (dossierTables != null && dossierTables.size() > 0 ? Integer.parseInt(dossierTables.get(dossierTables.size() - 1).get("INDEX").toString()) : 0) + 1;

        List<SQLiteArgument> execSqls = new ArrayList<>();
        String tableName = null;
        int index = 0;
        for (DossierFileCatalog item : dossierFiles) {
            if (tables.containsKey(item.getWJXH())) {
                continue;
            }
            if (index % 2000 == 0) {
                tableName = String.format("yx_dzjz_jztpl_%s", pageIndex++);

                execSqls.add(EvidenceMaterialServer.generateTable(tableName));
            }
            tables.put(item.getWJXH(), tableName);
            execSqls.add(EvidenceMaterialServer.addTableRelation(tableName, item));
            index++;
        }

        Map<String, Object> res = new HashMap<>();
        res.put("table", tables);
        res.put("sqls", execSqls);

        return res;
    }

}
